package com.flushbonading.classsystem.service.impl;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.flushbonading.classsystem.constants.StateMsg;
import com.flushbonading.classsystem.entity.CommonResult;
import com.flushbonading.classsystem.entity.User;
import com.flushbonading.classsystem.entity.vo.LoginVO;
import com.flushbonading.classsystem.mapper.UserMapper;
import com.flushbonading.classsystem.service.ConfigService;
import com.flushbonading.classsystem.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author zyx 2134208960@qq.com
 * @date 2021/11/8 16:58
 * @since 1.0.0
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ConfigService configService;

    @Override
    public User getUserByUserId(String userId) {
        return userMapper.getUserByUserId(userId);
    }

    @Override
    public CommonResult insertUser(Map<String, Object> params) {
        //校验填写的账号
        if (!params.containsKey("userId") || params.get("userId")==null || ((String)params.get("userId")).length()<=0 ) {
            return CommonResult.error(StateMsg.EMPTY_USER_ID);
        }
        //校验填写的密码
        if (!params.containsKey("password") || params.get("password")==null || ((String)params.get("password")).length()<=0) {
            return CommonResult.error(StateMsg.EMPTY_PASSWORD);
        }
        //校验用户类型
        if (!params.containsKey("type") || params.get("type")==null || !existType((Integer) params.get("type"))) {
            return CommonResult.error(StateMsg.ERROR_USER_TYPE);
        }
        // TODO:校验角色类型,在创建完角色模块后还需修改
        if (!params.containsKey("roleId") || params.get("roleId")==null) {
            return CommonResult.error(StateMsg.ERROR_ROLE_TYPE);
        }
        //生成盐值
        String salt = RandomUtil.randomStringUpper(8);
        //生成加密后密码 MD5+BASE64
        String password = Base64.encode(SecureUtil.md5((String)params.get("password")+salt));

        User user = User.builder()
                .userId((String) params.get("userId"))
                .salt(salt)
                .password(password)
                .roleId(Short.parseShort(params.get("roleId").toString()))
                .type(Short.parseShort(params.get("type").toString())).build();
        //插入到用户表
        Integer result = userMapper.insertUser(user);
        //成功
        if (result!=null){
            return CommonResult.success(StateMsg.CREATE_USER_SUCCESS);
        }
        //失败
        return CommonResult.error(StateMsg.CREATE_USER_ERROR);
    }

    /**
     * 判断是否存在该类型
     * @param type 用户类型ID
     * @return
     */
    @Override
    public Boolean existType(Integer type) {
        List<Map> userType = configService.getConfig("user_type");
        if (userType.size()<=1){
            return false;
        }
        for (Map map :userType) {
            if (map.containsKey("ID") && ((Integer)map.get("ID"))==type){
                return true;
            }
        }
        return false;
    }

    @Override
    public CommonResult login(LoginVO loginVO) {
        //校验用户名
        String userId = loginVO.getUserId();
        if (userId==null || userId.length()<=0) {
            return CommonResult.error(StateMsg.EMPTY_USER_ID);
        }
        User user = getUserByUserId(userId);
        if (user==null) {
            return CommonResult.error(StateMsg.USER_NOT_FOUND);
        }
        //取出盐值
        String userSalt = user.getSalt();
        String tempPassword = Base64.encode(SecureUtil.md5(loginVO.getPassword() + userSalt));
        //校验和数据库存储的是否相同
        if (!tempPassword.equals(user.getPassword())) {
            return CommonResult.error(StateMsg.PARAMS_ERROR);
        }
        return CommonResult.success(StateMsg.LOGIN_SUCCESS);
    }
}
